<template>
    <view style="padding: 15px;">
        <u-form ref="validateFormRef" :model="validateForm.value" :label-width="150">
            <u-form-item label="商品缩略图" prop="sysFileId" required>
                <u-upload ref="uUpload" :multiple="false" :auto-upload="false" :max-count="1" :show-progress="false" :file-list="fileList"
                          @on-remove="onRemove($event)" @on-choose-complete="onChooseComplete($event)"></u-upload>
            </u-form-item>
            <u-form-item label="编码" prop="code" required>
                <u-input v-model="validateForm.value.code" placeholder="请输入编码"/>
            </u-form-item>
            <u-form-item label="名称" prop="name" required>
                <u-input v-model="validateForm.value.name" placeholder="请输入名称"/>
            </u-form-item>
            <u-form-item label="显示顺序" prop="displayOrder">
                <u-input v-model="validateForm.value.displayOrder" placeholder="请输入显示顺序（可选）"/>
            </u-form-item>
        </u-form>

        <u-button type="error" @click="submit">提交</u-button>
    </view>
</template>

<script>
    import {CommonService} from "@/dev/services/common.service";
    import {SysFileService} from "@/dev/services/sys-file.service";
    import {CommonUtil} from "@/dev/core/utils/common.util";
    import {QiniuCloudUtil} from "@/dev/core/utils/qiniu-cloud.util";
    import {TbGoodsColorService} from "@/dev/services/tb-goods-color.service";
    import {UFormUtil} from "@/dev/core/utils/u-form.util";

    export default {
        data() {
            return {
                fileList: [],
                validateForm: {
                    value: {
                        id: CommonUtil.randomUUID(),
                        goodsId: null,
                        sysFileId: '',  // 图片sysFile.id
                        code: '',
                        name: '',
                        displayOrder: '',
                    },
                    rules: {
                        sysFileId: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        code: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    new CommonService().uniqueCheckByFields({
                                        "tableName": "tb_goods_color",
                                        "fieldList": [
                                            {"fieldName": "goods_id", "fieldValue": this.validateForm.value.goodsId},
                                            {"fieldName": "code", "fieldValue": value},
                                        ],
                                        "excludeId": this.validateForm.value.id
                                    }).then(result => {
                                        if (result.status === "fail") {
                                            callback(new Error('输入编号已存在！'))
                                        } else {
                                            callback()
                                        }
                                    })
                                }
                            }
                        ],
                        name: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        displayOrder: [
                            {
                                pattern: /^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$/,
                                message: '请输入大于0的正数!',
                                trigger: ['change', 'blur']
                            }
                        ],
                    }
                }
            }
        },
        onReady() {
            const _self = this;
            UFormUtil.setDefaultValues(this.validateForm, this.objParams);
            new SysFileService().findQiniuCloudImageUrl({fkId: this.validateForm.value.id}).then(result => {
                if (result.url) {
                    _self.validateForm.value.sysFileId = result.id;
                    _self.fileList.push({
                        id: result.id,
                        url: result.url + "?_timestamp=" + new Date().getTime(),
                    });
                }
                _self.$forceUpdate()
            });
        },
        methods: {
            onRemove($event) {
                console.log($event);
                const _self = this;
                new SysFileService().deleteSysFile({
                    id: _self.validateForm.value.sysFileId
                }).then(result => {
                    _self.validateForm.value.sysFileId = '';
                    UFormUtil.validation(_self.$refs.validateFormRef, 'sysFileId');
                    CommonUtil.toast("图片删除成功");
                    _self.$forceUpdate()
                });
            },
            onChooseComplete($event) {
                console.log($event);
                const _self = this;
                QiniuCloudUtil.uploadToCloud(_self.validateForm.value.id, $event[$event.length - 1].file.path).then(result => {
                    if (result.status === "success") {
                        _self.validateForm.value.sysFileId = result.id;
                        CommonUtil.toast(result.message);
                    } else {
                        CommonUtil.alert(result.message);
                    }
                    UFormUtil.validation(_self.$refs.validateFormRef, 'sysFileId');
                });
            },
            submit() {
                const _self = this;
                this.$refs.validateFormRef.validate(valid => {
                    if (valid) {
                        console.log('验证通过', _self.validateForm.value);
                        CommonUtil.alert({
                            title: '提示！',
                            content: '确认提交吗？',
                            showCancel: true, // 是否显示取消按钮
                            success: function (res) {
                                if (res.cancel) { // 点击取消,默认隐藏弹框
                                } else { // 点击确定
                                    new TbGoodsColorService().updateTbGoodsColor(_self.validateForm.value).then(result => {
                                        CommonUtil.toastNavigateBack('更新成功');
                                        Object.assign(_self.objParams, CommonUtil.deleteNullAttrInObject(result));
                                    });
                                }
                            }
                        });
                    } else {
                        console.log('验证失败');
                    }
                });
            }
        }
    };
</script>

<style lang="scss" scoped>
</style>
